#include "../header/msgstream.hpp"

#include "../header/common_conf.hpp"

msgstream::msgstream(Mode _mode,const char* out_name,int _onePieceSize){
    this->mode = _mode;
    this->onePieceSize = _onePieceSize;
    strcpy(fileName,out_name);

    MLOG(out_name);
    if(mode == READ) {
        ifs.open(fileName, ios::in | ios::binary);
        if(!ifs.is_open()){
            MLOG("NO SUCH FILE");
            exit(1);
        }
        ifs.seekg(0,ios::end);
        this->fileSize=ifs.tellg();
        ifs.seekg(0,ios::beg);
        assert(ifs.is_open());
        if(this->fileSize<0){
            MLOG("file is too large");
            exit(1);
        }
    } else {
        ofs.open(fileName, ios::out | ios::trunc | ios::binary);
    }
}

// move a valiable piece from input file to output file 
// with the io pointer move together.
// copy the data to buffer
// return the real size of copy data  
size_t msgstream::writePiece(char* buffer,int Write_size){
    if(mode==READ)
        return -1;

    ofs.write(buffer,Write_size);
    return Write_size;
}

size_t msgstream::readPiece(char* buffer){
    if(mode == WRITE){
        return -1;
    }

    ifs.read(buffer,onePieceSize);
    if(ifs){
        return onePieceSize;
    } else {
        return ifs.gcount();
    }
}

void msgstream::close(){
    if(mode==READ) {
        ifs.close();
    } else {
        ofs.close();
    }
    cout<<"file stream close"<<endl;
}

size_t msgstream::setPosition(unsigned long offset){  
    ifs.seekg(offset,ios::beg);
    return 0;
}